package com.haven.android.sdk.utils;

import android.util.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class HavenAesUtils {

    // 将字符串密钥转换为 AES 密钥
    public static SecretKeySpec getKeyFromString(){
        try {
            // 使用 SHA-256 对字符串进行哈希，以确保生成 256 位的密钥
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] bytes = digest.digest("System.arrayCopy".getBytes(StandardCharsets.UTF_8));
            return new SecretKeySpec(bytes, "AES");
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    // 使用 AES 加密
    public static String encrypt(String data){
        try {
            SecretKeySpec key = HavenAesUtils.getKeyFromString();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";

    }

    // 使用 AES 解密
    public static String decrypt(String encryptedData) {
        try {
            SecretKeySpec key = getKeyFromString();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decodedBytes = Base64.decode(encryptedData, Base64.DEFAULT);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        }catch (Exception e){
            e.printStackTrace();
        }
       return "";
    }
}
